<template>
  <div class="alipay-payment">
    <!-- 支付弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="400px"
      center
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div class="payment-content">
        <!-- 套餐信息 -->
        <div class="package-info">
          <div class="package-name">{{ packageInfo.name }}</div>
          <div class="package-price">¥ {{ packageInfo.price }}</div>
        </div>
        
        <!-- 支付状态提示 -->
        <div v-if="paymentStatus.message" :class="['payment-status', paymentStatus.success ? 'success' : 'error']">
          <el-icon v-if="paymentStatus.success"><Check /></el-icon>
          <el-icon v-else><Close /></el-icon>
          <span>{{ paymentStatus.message }}</span>
        </div>
        
        <!-- 支付宝支付表单容器 -->
        <div v-if="paymentFormHtml" class="alipay-form-container">
          <p>请点击下方按钮跳转至支付宝支付</p>
          <div class="alipay-button-container">
            <div v-html="paymentFormHtml"></div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="loading">
            {{ loading ? '处理中...' : '确认支付' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 加载提示 -->
    <div v-if="loading && !dialogVisible" class="loading-overlay">
      <div class="loading-spinner">
        <el-icon><Loading /></el-icon>
        <span>{{ loadingText }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading, Check, Close } from '@element-plus/icons-vue';
import { rechargePackage, checkOrderStatus } from '@/api/chat';

// 组件属性定义
const props = defineProps({
  // 弹窗标题
  title: {
    type: String,
    default: '支付宝支付'
  },
  // 套餐信息
  packageInfo: {
    type: Object,
    default: () => ({ type: '', name: '默认套餐', price: 0 })
  }
});

// 组件事件
const emit = defineEmits(['success', 'cancel', 'error', 'close']);

// 组件状态
const dialogVisible = ref(false);
const loading = ref(false);
const loadingText = ref('正在处理支付请求...');
const paymentStatus = ref({ success: false, message: '' });
const paymentFormHtml = ref('');
const orderSn = ref('');

// 轮询相关变量
const orderTimer = ref(null);
const MAX_CHECK_TIMES = 20;
const checkTimes = ref(0);

// 打开支付弹窗
const showPayment = () => {
  dialogVisible.value = true;
  // 重置状态
  paymentStatus.value = { success: false, message: '' };
  paymentFormHtml.value = '';
  orderSn.value = '';
  checkTimes.value = 0;
  // 停止之前可能存在的订单检查
  stopOrderCheck();
};

// 关闭弹窗
const handleClose = () => {
  stopOrderCheck();
  dialogVisible.value = false;
  emit('close');
};

// 确认支付
const confirmPayment = async () => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    loadingText.value = '正在创建订单...';
    
    // 获取设备类型，用于后端判断使用何种支付方式
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    
    // 创建订单并获取支付信息
    const params = {
      user_phone: localStorage.getItem('userphone'),
      combo_type: props.packageInfo.type,
      amount: props.packageInfo.price, // 添加金额参数，与后端保持一致
      pay_type: 'alipay', // 标明使用支付宝支付
      is_mobile: isMobile // 传递设备类型
    };
    
    const res = await rechargePackage(params);
    
    if (res.code === 0 && res.data) {
      // 保存订单号，用于后续查询
      orderSn.value = res.data.order_sn;
      
      if (res.data.pay_type === 'alipay' && res.data.html) {
        // 设置支付宝表单HTML
        paymentFormHtml.value = res.data.html;
        
        // 自动模拟点击表单提交按钮，跳转到支付宝
        setTimeout(() => {
          const form = document.querySelector('.alipay-form-container form');
          if (form) {
            form.submit();
            // 开始检查订单状态
            startCheckOrderStatus(orderSn.value);
          } else {
            ElMessage.error('支付表单加载失败，请重试');
            loading.value = false;
          }
        }, 500);
      } else {
        ElMessage.error('支付信息获取失败，请重试');
        loading.value = false;
      }
    } else {
      ElMessage.error(res.msg || '创建订单失败，请重试');
      loading.value = false;
    }
  } catch (error) {
    console.error('支付处理错误:', error);
    ElMessage.error('支付处理出错，请重试');
    loading.value = false;
  }
};

// 开始轮询订单状态
const startCheckOrderStatus = (orderNumber) => {
  // 先停止可能存在的定时器
  stopOrderCheck();
  
  // 创建新的定时器，每3秒检查一次订单状态
  orderTimer.value = setInterval(async () => {
    try {
      checkTimes.value++;
      
      if (checkTimes.value > MAX_CHECK_TIMES) {
        stopOrderCheck();
        paymentStatus.value = { 
          success: false, 
          message: '订单支付状态查询超时，请刷新页面重试或联系客服' 
        };
        return;
      }
      
      const result = await checkOrderStatus(orderNumber);
      
      if (result && result.code === 0) {
        // 支付成功
        if (result.data && result.data.pay_status === 1) {
          stopOrderCheck();
          paymentStatus.value = { 
            success: true, 
            message: '支付成功！' 
          };
          loading.value = false;
          
          // 通知父组件支付成功
          emit('success', { 
            orderSn: orderNumber, 
            packageInfo: props.packageInfo 
          });
          
          // 3秒后关闭弹窗
          setTimeout(() => {
            handleClose();
          }, 3000);
        }
      }
    } catch (error) {
      console.error('查询订单状态错误:', error);
    }
  }, 3000);
};

// 停止订单检查
const stopOrderCheck = () => {
  if (orderTimer.value) {
    clearInterval(orderTimer.value);
    orderTimer.value = null;
  }
};

// 在组件卸载前清除定时器
onBeforeUnmount(() => {
  stopOrderCheck();
});

// 暴露组件方法
defineExpose({
  showPayment
});
</script>

<style scoped>
.payment-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.package-info {
  text-align: center;
  margin-bottom: 20px;
}

.package-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.package-price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.payment-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  border-radius: 4px;
  margin: 15px 0;
  width: 100%;
}

.payment-status.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.payment-status.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.payment-status .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

.alipay-form-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 15px 0;
}

.alipay-form-container p {
  margin-bottom: 15px;
  color: #606266;
}

.alipay-button-container {
  width: 100%;
}

.alipay-button-container :deep(button),
.alipay-button-container :deep(input[type="submit"]) {
  width: 100%;
  padding: 10px;
  background-color: #1677ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-spinner {
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner .el-icon {
  font-size: 24px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 适配移动端 */
@media screen and (max-width: 768px) {
  .package-name {
    font-size: 16px;
  }
  
  .package-price {
    font-size: 20px;
  }
}
</style>
